package gwtappcontainer.testhelpers;

import static org.junit.Assert.assertTrue;
import gwtappcontainer.server.apps.security.SecurityAPI;
import gwtappcontainer.shared.apis.APIResponse;

import java.io.File;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;

public class APITestHelper3 {
	
	private String email = "testhelper@testhelper.com";
	
	private final LocalServiceTestHelper dataStoreTestHelper =
	        new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
	    
    private final LocalServiceTestHelper userServiceTestHelper =
	        new LocalServiceTestHelper(new LocalUserServiceTestConfig())
	            .setEnvIsLoggedIn(false)
	            .setEnvAuthDomain("example.com")
	            .setEnvEmail(email);
               
    public User getUser() {
    	return UserServiceFactory.getUserService().getCurrentUser();
    }        
              
    public User loginAsInvalidUser() {
    	
    	//first delete userentity (if present) by logging as admin
    	SecurityAPI api = new SecurityAPI();
    	api.deleteUser(email, loginAsSuperUser());
    	
    	//change to non-admin
    	userServiceTestHelper.setEnvIsLoggedIn(true)
		.setEnvEmail(email).setEnvIsAdmin(false);
    	
    	return UserServiceFactory.getUserService().getCurrentUser();
    }
    
    public User loginAsValidUser() {  
    	//logs in as a valid user that exists in ishaportal security userentity
    	
    	SecurityAPI api = new SecurityAPI();
    	api.addUser(email, loginAsSuperUser());
    	
    	userServiceTestHelper.setEnvEmail(email);
    	return UserServiceFactory.getUserService().getCurrentUser();
    }
    
    public User loginWithPrivilege(String privilege) {
    	    	
    	SecurityAPI api = new SecurityAPI();
    	@SuppressWarnings("unused")
		APIResponse response = api.addPrivilege(privilege, loginAsSuperUser()); 
    	
    	//delete user if exists and add it again
    	response = api.deleteUser(email, loginAsSuperUser());
    	    	
    	response = api.addUser(email, loginAsSuperUser());    	    	
    	
    	response = api.assignPrivilegeToUser(email, privilege, loginAsSuperUser());    	    	
    	
    	userServiceTestHelper.setEnvEmail(email);
    	return UserServiceFactory.getUserService().getCurrentUser();
    }      
    
    
    public User loginAsSuperUser() {
    	final String SUPER_USER = "sathyanarayanant@gmail.com";
    	//ugly hack required 
    	userServiceTestHelper.setEnvIsLoggedIn(true)
    		.setEnvEmail(SUPER_USER).setEnvIsAdmin(true);
    	
    	return UserServiceFactory.getUserService().getCurrentUser();
    }
    
    public String getEmail() {
    	return email;
    }       
        
	public void setUp() {
		
		dataStoreTestHelper.setUp();
		userServiceTestHelper.setUp();				 			
	}
	
	public void tearDown() {		
		userServiceTestHelper.tearDown();
		
		
		
		try {
			dataStoreTestHelper.tearDown();
		} catch (Exception e) {
			// data store test helper throws null pointer exception 
			// when used userservice test helper
			
			//swallow the exception for now as a temporary hack till the root cause
			//is identified
		}
		
		//deleteTempFiles();
	}		
	
	@SuppressWarnings("unused")
	private void deleteTempFiles() {
		String workingDir = System.getProperty("user.dir");
		System.out.println("Working Directory = " +
	              System.getProperty("user.dir"));
		
		String dataDir = workingDir + "\\WEB-INF\\appengine-generated\\";
		String dbBinFile = dataDir + "local_db.bin";
		String indexesFile = dataDir + "datastore-indexes-auto.xml";
		
		try {
			File file = new File(dbBinFile);
			file.delete();
			file = new File(indexesFile);
			file.delete();
			assertTrue(true);
		
		} catch (Exception ex) {
			System.out.println("exception when deleting temp files: " 
				+ ex.getMessage());			
		}
	}
}
